package com.dingding.service.coupon;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.District;
import com.dingding.common.core.beans.Promotionstat;
import com.dingding.common.core.beans.UserLogin;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.facde.activity.dto.CouponStoreDTO;
import com.dingding.facde.activity.dto.ExpiredCouponDTO;
import com.dingding.facde.activity.dto.ReceiveCouponDTO;
import com.dingding.facde.activity.dto.ShowUserCouponDTO;
import com.dingding.facde.activity.dto.ShowUserCouponListDTO;
import com.dingding.facde.activity.dto.UserCouponInfoDTO;
import com.dingding.facde.coupon.ICouponService;
import com.dingding.service.activity.core.dao.IAdvertiseStatDao;
import com.dingding.service.activity.core.dao.ICouponDao;
import com.dingding.service.activity.core.dao.IDistrictDao;
import com.dingding.service.activity.core.dao.IPromotionstatDao;
import com.dingding.service.activity.core.dao.IUserCouponDao;
import com.dingding.service.common.core.dao.IPhonevalidateDao;
import com.dingding.service.common.core.dao.IUserAccountDao;
import com.dingding.service.common.core.dao.IUserDetailDao;
import com.dingding.service.common.core.dao.IUserIntegralDao;
import com.dingding.service.common.core.dao.IUserLoginDao;
import com.dingding.service.common.core.dao.IVehicleinfoDao;
import com.dingding.service.store.dao.ICouponStoreDao;

/**
 * 
 * @ClassName: UserCouponDataServiceImpl
 * @Description: 用户优惠券数据服务
 * @author CHEHAUNBO
 * @date 2016年2月19日 上午10:53:35
 * 
 */
@Component("couponService")
public class CouponServiceImpl implements ICouponService {

	private Logger log = Logger.getLogger(this.getClass());

	// 用户优惠券DAO
	@Resource
	protected IUserCouponDao userCouponDao;

	// 优惠券DAO
	@Resource
	protected ICouponDao couponDao;

	// 城市门店DAO
	@Resource
	protected ICouponStoreDao couponStoreDao;

	// 验证码DAO
	@Resource
	protected IPhonevalidateDao phonevalidateDao;

	// 用户详细信息DAO
	@Resource
	protected IUserDetailDao userDetailDao;

	// 用户登录DAO
	@Resource
	protected IUserLoginDao userLoginDao;

	// 用户积分DAO
	@Resource
	protected IUserIntegralDao userIntegralDao;

	// 用户账号DAO
	@Resource
	protected IUserAccountDao userAccountDao;

	@Resource
	protected IVehicleinfoDao vehicleinfoDao;

	@Resource
	protected IAdvertiseStatDao advertiseStatDao;

	@Resource
	protected IUserInfoFacade userInfoFacade;

	@Resource
	protected IDistrictDao districtDao;

	@Resource
	protected IPromotionstatDao promotionstatDao;

	/**
	 * @Title: getUserCouponList
	 * @Description: 根据用户ID获取当前用户的所有优惠券
	 * @param userId
	 *            用户优惠券ID
	 * @return List<ShowUserCouponDTO> 查询到的当前用户的优惠券集合
	 * @author CHEHAUNBO
	 */
	@Override
	public List<ShowUserCouponDTO> getUserCouponList(String userId) {

		// 判断传入的参数是否为空
		if (ToolUtil.isBlank(userId)) {
			return null;
		}

		List<ShowUserCouponDTO> coupons = this.userCouponDao.getUserCouponList(userId);

		return coupons;
	}

	/**
	 * @Title: getUserCoupons
	 * @Description: 根据用户ID获取当前用户的所有优惠券
	 * @param userId
	 *            用户优惠券ID
	 * @return List<ShowUserCouponDTO> 查询到的当前用户的优惠券集合
	 * @author CHEHAUNBO
	 */
	@Override
	public List<ShowUserCouponListDTO> getUserCoupons(String userId) {

		// 判断传入的参数是否为空
		if (ToolUtil.isBlank(userId)) {
			return null;
		}

		List<ShowUserCouponListDTO> coupons = this.userCouponDao.getUserCoupons(userId);

		return coupons;
	}
	
	/**
	 * @Title: getUserCouponInfo
	 * @Description: 根据用户ID获取优惠券详细信息 主要包括：规则、有效期、金额
	 * @param userCouponId
	 *            用户优惠券ID
	 * @return UserCouponInfoDTO 用户详情
	 * @author CHEHAUNBO
	 */
	@Override
	public UserCouponInfoDTO getUserCouponInfo(String userCouponId) {

		// 判断传入的参数是否为空
		if (ToolUtil.isBlank(userCouponId)) {
			return null;
		}

		return this.userCouponDao.getUserCouponInfo(userCouponId);
	}

	/**
	 * @Title: activateCoupon
	 * @Description: 激活优惠券
	 * @param userCouponId
	 *            用户优惠券主键ID
	 * @return boolean true 激活成功 false 激活失败
	 * @author CHEHAUNBO
	 */
	@Override
	public boolean activateCoupon(String userCouponId) {

		// 判断传入的参数是否为空
		if (ToolUtil.isBlank(userCouponId)) {
			return false;
		}

		return this.userCouponDao.activateCoupon(userCouponId);
	}

	/**
	 * @Title: useCoupon
	 * @Description: 使用优惠券
	 * @param couponId
	 *            优惠券id
	 * @param userId
	 *            扫码人
	 * @author fengshuonan
	 * @return boolean true 使用成功 false 使用失败
	 * @Override
	 */
	public boolean useCoupon(String couponId, String userId) {

		if (ToolUtil.isBlank(couponId) || ToolUtil.isBlank(userId)) {
			return false;
		}

		return this.userCouponDao.useCoupon(couponId, userId);
	}

	/**
	 * @Title: generateCoupon
	 * @Description:领取优惠券
	 * @param receive
	 * @author fengshuonan
	 * @return int
	 * @Override
	 */
	public int generateCoupon(ReceiveCouponDTO receive) {

		// 手机号
		String tellPhone = receive.getTellPhone();
		// 验证码
		String validateNum = receive.getVaidateNum();
		// WechatId
		String weChatId = receive.getWeChatId();

		// 1:判断验证码是否正确
		boolean isSuccess = this.phonevalidateDao.verificationCode(tellPhone, validateNum);
		if (!isSuccess) {
			return 1; // 验证码错误
		}

		// 2:判断是否首次注册用户（1: 存在用户，但是未参加活动 2: 存在用户，但是已经参加活动 3:用户不存在）
		int status = this.userLoginDao.isExistUserByUserName(tellPhone);

		switch (status) {
		case 1: // 1: 存在用户，但是未参加活动
			this.addUserCoupon(tellPhone);
			break;
		case 2:// 2: 存在用户，但是已经参加活动
				// 绑定微信ID
			this.userLoginDao.bindingWeChatId(tellPhone, weChatId);
			break;
		case 3: // 3:用户不存在
			// this.addUser(tellPhone, weChatId); // 初始化用户
			this.regUser(tellPhone, weChatId);// 注册用户
			this.addUserCoupon(tellPhone);// 给用户添加优惠券
			break;
		}

		return 2;
	}

	/**
	 * @Title: activeCouponByTel
	 * @Description: 根据手机号和优惠券类型激活优惠券
	 * @param tellphone
	 * @author fengshuonan
	 * @return boolean
	 * @Override
	 */
	public boolean activeCouponByTel(String tellphone) {

		if (ToolUtil.isBlank(tellphone)) {
			return false;
		}

		return this.userCouponDao.weChatActivationCoupon(tellphone);
	}

	/**
	 * @Description: 判断是否存在openid
	 * @author fengshuonan
	 * @return boolean
	 */
	@Override
	public boolean isExistOpenId(String openId) {

		if (ToolUtil.isBlank(openId)) {
			return false;
		}

		return this.userLoginDao.isExistUserByWeChatId(openId);
	}

	/**
	 * @Title: isExistUserByWeChatId
	 * @Description: 通过微信ID判断当前用户是否已经和手机号绑定
	 * @param openId
	 *            weChatId 用户微信ID
	 * @author fengshuonan
	 * @return boolean true 存在 false 失败
	 */
	@Override
	public boolean isExistUserByWeChatId(String phone, String openId) {

		if (ToolUtil.isNotBlank(phone) && ToolUtil.isBlank(openId)) {
			return false;
		}

		// 如果用户手机号存在，更新用户的openId
		this.userLoginDao.updateUserWechatId(phone, openId);

		return this.userLoginDao.isExistUserByWeChatId(openId);
	}

	/**
	 * @Title: addAdvertiseClickNum
	 * @Description: 增加推广公司相应的统计次数
	 * @param asId
	 *            推广公司的id
	 * @param type
	 *            统计操作的类型（1：点击 2：分享 3：注册）
	 * @author fengshuonan
	 * @Override
	 */
	public void addAdvertiseNum(String asId, int type) {

		if (ToolUtil.isBlank(asId) || type == 0) {
			log.info("增加推广公司统计次数的时候,推广公司的id为空或类型为空！CouponServiceImpl：addAdvertiseNum()" + "asId=" + asId + ",type="
					+ type);
			return;
		}

		this.advertiseStatDao.addAdvertiseNum(asId, type);
	}

	/**
	 * 
	 * @Title: addUserCoupon
	 * @Description: 添加用户优惠券
	 * @author CHEHAUNBO
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void addUserCoupon(String tellPhone) {

		UserLogin userLogin = this.userLoginDao.getUserLoginByProperty("userName", tellPhone);

		if (userLogin != null) {
			String userId = userLogin.getUid();
			userLogin.setCouponNumber(2);
			userLogin.setIsAttendActivity(2);
			this.userCouponDao.addUserCoupon(userId);
		}
	}

	/**
	 * @Title: addUser
	 * @Description: 添加用户优惠券
	 * @param tellPhone
	 *            手机号
	 * @return boolean true 添加成功 false 添加失败
	 * @author CHEHAUNBO
	 * @deprecated
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addUser(String tellPhone, String weChatId) {

		String userLoginId = ToolUtil.getUid();
		try {
			// 首次注册初始化用户所有信息
			// 添加用户
			this.userLoginDao.addUserLogin(tellPhone, userLoginId, weChatId);
			// 添加用户详细信息
			this.userDetailDao.addUserDetail(tellPhone, userLoginId);
			// 添加用户账户信息
			this.userAccountDao.addUserAccount(userLoginId);
			// 添加用户积分信息
			this.userIntegralDao.addUserIntegral(userLoginId);
			// 添加用户车辆信息
			this.vehicleinfoDao.addVehicleInfo(userLoginId);
		} catch (Exception e) {
			log.error("初始化用户出现异常");
		}

		// 首先判断
		return false;
	}

	/**
	 * @Description: 注册用户
	 * @param tellphone
	 *            电话号
	 * @param weChatId
	 *            微信id
	 * @return
	 * @author fengshuonan
	 * @return boolean
	 */
	private boolean regUser(String tellphone, String weChatId) {

		return this.userInfoFacade.addUser(tellphone, weChatId);
	}

	/**
	 * @Title: geCouponStoreDTOs @Description: 根据城市名称获取门店信息 @param cityName
	 * 城市名称 @author YHQ @return List<CouponStoreDTO> @throws
	 */
	@Override
	public List<CouponStoreDTO> geCouponStoreDTOs(String cityName) {
		return this.couponStoreDao.getCouponStoreList(cityName);
	}

	/**
	 * 
	 * @Title: addUserCoupon
	 * @Description: 添加用户优惠券
	 * @param telPhone
	 *            电话号码
	 * @author cw
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void addUserCouponInfo(String telPhone) {

		UserLogin userLogin = this.userLoginDao.getUserLoginByProperty("userName", telPhone);

		if (userLogin != null) {
			String userId = userLogin.getUid();
			userLogin.setCouponNumber(1);
			userLogin.setIsAttendActivity(1);
			this.userCouponDao.addUserCouponInfo(userId);
		}
	}

	/**
	 * 
	 * @Title: addUserCoupon
	 * @Description: 添加用户优惠券
	 * @param userId
	 *            用户Id
	 * @author cw
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void addUserCouponInfoUserId(String userId) {
		this.userCouponDao.addUserCouponInfo(userId);
	}

	/**
	 * 
	 * @Title: useCoupon
	 * @Description: 使用优惠券(用户在搭车过程中的优惠券变化)
	 * @param ucid
	 *            用户优惠券Id
	 * @param type
	 *            优惠券状态
	 * @author YHQ
	 * @return void 返回类型
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean useCoupon(String ucid, Integer couponType) {

		return userCouponDao.useCouponByUser(ucid, couponType);
	}

	/**
	 * @Description: 添加现金优惠券
	 * @param telPhone
	 *            电话号码
	 * @author fengshuonan
	 * @return void
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void addMoneyCoupon(String tellphone) {

		UserLogin userLogin = this.userLoginDao.getUserLoginByProperty("userName", tellphone);

		if (userLogin != null) {
			String userId = userLogin.getUid();
			userLogin.setCouponNumber(1);
			userLogin.setIsAttendActivity(2);
			this.userCouponDao.addMoneyCoupon(userId, true);
		}
	}

	/**
	 * @Description:添加洗车券和现金券
	 * @param tellphone
	 *            电话号码
	 * @author fengshuonan
	 * @return void
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void addCarWashCouponAndMoneyCoupon(String tellphone) {

		UserLogin userLogin = this.userLoginDao.getUserLoginByProperty("userName", tellphone);

		if (userLogin != null) {
			String userId = userLogin.getUid();
			userLogin.setCouponNumber(2);
			userLogin.setIsAttendActivity(2);
			this.userCouponDao.addCarWashCouponAndMoneyCoupon(userId, true);
		}
	}

	/**
	 * @Description:获取推广号的所属区域信息
	 * @param promotionId 推广号id
	 * @author fengshuonan
	 * @return District
	 */
	@Override
	@Transactional(readOnly = true)
	public District getDistrictByDistrictId(String promotionId) {

		if (ToolUtil.isBlank(promotionId)) {
			return null;
		}
		
		Promotionstat promotionstat = null;
		District district = null;
		
		try {
			promotionstat = this.promotionstatDao.getById(promotionId);
		} catch (Exception e) {
			log.error("获取推广号的所属区域信息出错！CouponServiceImpl:getDistrictByDistrictId()",e);
			return null;
		}
		
		if(promotionstat != null){
			
			Integer districtId = promotionstat.getDistrictId();
			
			if(districtId != null && districtId != 0){
				
				try {
					district = this.districtDao.getById(districtId);
				} catch (Exception e) {
					log.error("获取推广号的所属区域信息出错！CouponServiceImpl:getDistrictByDistrictId()",e);
					return null;
				}
				
				if(district != null){
					return district;
				}
			}
		}

		return null;
	}

	/**
	 * 
	 * @Title: getExpiredCouponNumber 
	 * @Description: 获取即将过期优惠券数量
	 * @param userId 用户Id
	 * @author YHQ 
	 * @since V2.6.3
	 * @return ExpiredCouponDTO    返回类型
	 * 
	 */
	@Override
	public ExpiredCouponDTO getExpiredCouponNumber(String userId) {
		
		if(ToolUtil.isNotBlank(userId)){
			return null;
		}
		
		return userCouponDao.getExpiredCouponNumber(userId);
	}

}
